package com.kingsalert.kingsalert.activity;

import androidx.viewpager2.widget.ViewPager2;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.kingsalert.kingsalert.analytics.event.IAnalyticsEvent;
import com.kingsalert.kingsalert.analytics.util.AnalyticsUtil;
import com.kingsalert.kingsalert.R;
import com.kingsalert.kingsalert.activity.ln.MainActivity;
import com.kingsalert.kingsalert.adapter.LoginCarouselAdapter;
import com.kingsalert.kingsalert.base.BaseActivity;
import com.kingsalert.kingsalert.bean.config.AppShowCustomize;
import com.kingsalert.kingsalert.bean.userinfo.LoginInfo;
import com.kingsalert.kingsalert.bean.userinfo.OthersInfo;
import com.kingsalert.kingsalert.config.CountryConfig;
import com.kingsalert.kingsalert.dialog.CustomerServiceDialog;
import com.kingsalert.kingsalert.util.UserInfoUtil;
import com.kingsalert.kingsalert.util.http.HttpUtil;
import com.kingsalert.kingsalert.view.NumberTextView_S;

import org.json.JSONException;
import org.json.JSONObject;

public class LoginActivity extends BaseActivity {

    private EditText mobileEt,vercodeEt;
    private Button getcodeBtn;
    private ImageButton agreementIb;

    private boolean agreementFlag = true;

    private final View.OnClickListener sendCodeCl = v -> {

        String mobile = mobileEt.getText().toString().trim();

        if (TextUtils.isEmpty(mobile)){
            Toast.makeText(this,getString(R.string.tips_enter_mobile),Toast.LENGTH_SHORT).show();
            return;
        }

        HttpUtil.getInstance().requestOtpCode(this,mobile,this::onSendCodeResponse);
    };

    private final View.OnClickListener loginCl = v -> {

        String mobile = mobileEt.getText().toString().trim();
        String vercode = vercodeEt.getText().toString().trim();

        HttpUtil.getInstance().saveBuriedPoint(page,"CONFIRM_CLICK",mobile);

        if (TextUtils.isEmpty(mobile)){
            Toast.makeText(this,getString(R.string.tips_enter_mobile),Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(vercode)){
            Toast.makeText(this,getString(R.string.tips_enter_vercode),Toast.LENGTH_SHORT).show();
            return;
        }

        //测试账号自动登录
        if (AppShowCustomize.getInstance().isTestAccount(mobile)){
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("token", AppShowCustomize.getInstance().getTestToken(mobile));
                jsonObject.put("userId", mobile);
                jsonObject.put("type", UserInfoUtil.LOGIN_TYPE_OLD);
                jsonObject.put("isAdSource","NO");
                LoginInfo.parse(jsonObject);
                onLoginSuccessResponse();
            }catch (JSONException e){
                e.printStackTrace();
            }
            return;
        }

        HttpUtil.getInstance().userLg(this,mobile,vercode,this::onLoginSuccessResponse);

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        page = "LOGIN";

        initCarousel();
        init();
    }

    private void initCarousel(){
        ViewPager2 carouselVp = findViewById(R.id.al_view_carousel);
        LoginCarouselAdapter loginCarouselAdapter = new LoginCarouselAdapter(this);
        carouselVp.setAdapter(loginCarouselAdapter);
        new Thread(() -> {
            try {
                Thread.sleep(2985);
                int count=-1;
                while (++count<Integer.MAX_VALUE){
                    runOnUiThread(() -> {
                        int next = carouselVp.getCurrentItem()+1;
                        if (next<Integer.MAX_VALUE-1) carouselVp.setCurrentItem(next);
                    });
                    Thread.sleep(3126);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private void init(){

        findViewById(R.id.alg_ib_customerservice).setOnClickListener(v -> new CustomerServiceDialog(this).show());

        NumberTextView_S loanamountNtv = findViewById(R.id.alg_ntv_loanamount);
        NumberTextView_S interestrateNtv = findViewById(R.id.alg_ntv_interestrate);
        TextView interestratecycleTv = findViewById(R.id.alg_tv_interestratecycle);
        SeekBar amountSeekbar = findViewById(R.id.alg_seekbar_amount);
        TextView minamountTv = findViewById(R.id.alg_tv_minamount);
        TextView maxamountTv = findViewById(R.id.alg_tv_maxamount);

        TextView areacodeTv = findViewById(R.id.alg_tv_areacode);
        TextView mobiletitleTv = findViewById(R.id.alg_tv_mobiletitle);
        mobileEt = findViewById(R.id.alg_et_mobile);
        vercodeEt = findViewById(R.id.alg_et_vercode);
        getcodeBtn = findViewById(R.id.alg_btn_getcode);
        Button loginBtn = findViewById(R.id.alg_btn_login);
        agreementIb = findViewById(R.id.alg_ib_agreement);
        TextView agreementTv = findViewById(R.id.alg_tv_agreement);

        //肯尼亚手机号标题
        if (CountryConfig.getInstance().isKenya()){
            mobiletitleTv.setText(getString(R.string.login_mobile_title_kenya));
        }

        //初始化登录流程
        String areaCode = CountryConfig.getInstance().getAreaCode();
        areacodeTv.setText(areaCode);
        UserInfoUtil.getInstance().setAreaCode(areaCode);

        getcodeBtn.setOnClickListener(sendCodeCl);
        loginBtn.setOnClickListener(loginCl);

        //初始化协议
        agreementIb.setOnClickListener(v -> setAgreementFlag(!agreementFlag));
        agreementTv.setOnClickListener(v -> {
            HttpUtil.getInstance().saveBuriedPoint(page,"STATEMENT_CLICK","");
            String agreementUrl = AppShowCustomize.getInstance().getAgreementUrl();
            if (TextUtils.isEmpty(agreementUrl)) return;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(agreementUrl)));
        });

        //初始化额度显示
        interestrateNtv.setText(AppShowCustomize.getInstance().getLoginInterestRate());
        interestratecycleTv.setText(AppShowCustomize.getInstance().getLoginInterestRateCycle());

        String minAmountStr = AppShowCustomize.getInstance().getLoginMinAmount();
        String maxAmountStr = AppShowCustomize.getInstance().getLoginMaxAmount();
        String amountGranularityStr = AppShowCustomize.getInstance().getLoginAmountGranularity();

        minamountTv.setText(minAmountStr);
        maxamountTv.append(" "+maxAmountStr);

        loanamountNtv.setText(minAmountStr);

        try {
            int minAmount = Integer.parseInt(minAmountStr);
            int maxAmount = Integer.parseInt(maxAmountStr);
            int amountGranularity = Integer.parseInt(amountGranularityStr);

            amountSeekbar.setMin(minAmount/amountGranularity);
            amountSeekbar.setMax(maxAmount/amountGranularity);

            amountSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    loanamountNtv.setText(String.valueOf(seekBar.getProgress()*amountGranularity));
                }
                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {}
                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {}
            });
        }catch (NumberFormatException e){
            e.printStackTrace();
        }

        //验证码输入监听
        vercodeEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 4){

                    String mobile = mobileEt.getText().toString().trim();
                    String vercode = vercodeEt.getText().toString().trim();

                    HttpUtil.getInstance().saveBuriedPoint(page,"OTP_DONE",vercode);

                    if (TextUtils.isEmpty(mobile)) return;

                    //测试账号自动登录
                    if (AppShowCustomize.getInstance().isTestAccount(mobile)){
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("token", AppShowCustomize.getInstance().getTestToken(mobile));
                            jsonObject.put("userId", mobile);
                            jsonObject.put("type", UserInfoUtil.LOGIN_TYPE_OLD);
                            jsonObject.put("isAdSource","NO");
                            LoginInfo.parse(jsonObject);
                            onLoginSuccessResponse();
                        }catch (JSONException e){
                            e.printStackTrace();
                        }
                        return;
                    }

                    HttpUtil.getInstance().userLg(LoginActivity.this,mobile,vercode,() -> onLoginSuccessResponse());

                }
            }
        });

    }

    private void setAgreementFlag(boolean agreementFlag) {
        this.agreementFlag = agreementFlag;
        agreementIb.setBackgroundResource(agreementFlag ? R.drawable.icon_permission_agreement_check_true:R.drawable.icon_permission_agreement_check_false);
    }

    @SuppressLint("SetTextI18n")
    public void onSendCodeResponse(){

        Toast.makeText(this,getString(R.string.tips_vercode_send_success),Toast.LENGTH_SHORT).show();
        getcodeBtn.setOnClickListener(null);
        getcodeBtn.setBackgroundResource(R.drawable.bg_green_ll_rc24dp);

        //老用户直接登录
        String mobile = mobileEt.getText().toString().trim();
        JSONObject jsonObject = OthersInfo.getInstance().getSendOtpCodeJson();
        if (jsonObject!=null){
            String directLogin = jsonObject.optString("directLoginFlag");
            if (directLogin.equalsIgnoreCase("YES")) {
                HttpUtil.getInstance().userLoginOldUser(this,mobile,this::onLoginSuccessResponse);
                return;
            }
        }

        new Thread(() -> {

            int count = 60;

            while (count-- > 0){
                final int finalCount = count;
                runOnUiThread(() -> getcodeBtn.setText(finalCount+"s"));
                try {
                    Thread.sleep(999);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            runOnUiThread(() -> {
                getcodeBtn.setOnClickListener(sendCodeCl);
                getcodeBtn.setBackgroundResource(R.drawable.bg_green_main_rc24dp);
                getcodeBtn.setText(getString(R.string.get_code));
            });

        }).start();

    }

    public void onLoginSuccessResponse(){

        UserInfoUtil.getInstance().setMobile(mobileEt.getText().toString());
        UserInfoUtil.getInstance().setToken(LoginInfo.getInstance().getToken());
        UserInfoUtil.getInstance().setUserId(LoginInfo.getInstance().getUserId());
        UserInfoUtil.getInstance().setIsAdSource(LoginInfo.getInstance().getIsAdSource());

        if (LoginInfo.getInstance().getType().equalsIgnoreCase(UserInfoUtil.LOGIN_TYPE_REGISTER))
            AnalyticsUtil.INSTANCE.addEvent(IAnalyticsEvent.AT_REGISTER);

        AnalyticsUtil.INSTANCE.saveFirebaseAndFacebookS2SInfo();

        HttpUtil.getInstance().userProcess(this,this::onUserProcessResponse);

    }

    public void onUserProcessResponse(){
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

}